#include <vector>
#include <cstring>
#include <queue>
using namespace std;

class Solution {
public:
    int dx[4]={-1,1,0,0};
    int dy[4]={0,0,-1,1};
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        int n = maze.size(),m = maze[0].size();
        bool array[n][m];
        memset(array,0,sizeof(array));
        queue<pair<int,int>> q;
        q.push({entrance[0],entrance[1]});
        array[entrance[0]][entrance[1]]=true;
        int shorest_step=0;
        while(!q.empty())
        {
            ++shorest_step;
            int size = q.size(); //
            for(int i = 0;i<size;++i) //注意：如果是for(int i = 0;i<q.size();++i)就会少
            {
                int a = q.front().first, b = q.front().second;
                q.pop();
                for(int j = 0;j<4;++j)
                {
                    int x = a+dx[j];
                    int y = b+dy[j];
                    if(x>=0 && x<n && y>=0 && y<m && '.'== maze[x][y] && !array[x][y])
                    {
                        if(0 == x || n-1 == x || 0 == y || m-1 == y)
                        {
                            return shorest_step;
                        }
                        q.push({x,y});
                        array[x][y]=true;
                    }
                }
            }
        }
        return -1;
    }
};